// pages/Dashboard/QuickRightPanel.jsx
import React, { useState } from 'react';
import { useAuth } from 'contexts/AuthContext';
import { useMutation, useQuery, useQueryClient } from 'react-query';
import { CreateUser, CreateTeam, CreateWorkspace } from 'api/mutations';
import { CustomerCards, CustomerInvoices, Me, Workspaces, TestDatabaseConnection } from 'api/queries';
import {
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Paper,
  Typography,
  Menu,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Select,
  FormControl,
  InputLabel,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  CreditCard as PaymentIcon,
  Receipt as InvoiceIcon,
  Cable as TestIcon,
  PersonAdd as CreateUserIcon,
  GroupAdd as CreateTeamIcon,
  CreateNewFolder as CreateWorkspaceIcon,
  Refresh as RefreshIcon
} from '@mui/icons-material';

const QuickRightPanel = ({ 
  user, 
  borderRadius = 1, 
  border = 1, 
  borderColor = 'primary.main', 
  planType = 'basic', 
  role = 'user' 
}) => {
  const queryClient = useQueryClient();
  const [anchorEl, setAnchorEl] = useState(null);
  const [menuType, setMenuType] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState('');
  const [selectedValue, setSelectedValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [resultMessage, setResultMessage] = useState('');
  const [showResult, setShowResult] = useState(false);
  
  const isAdmin = user && (user.role === "admin" || user.role === "superadmin");
  
  // Queries
  const { refetch: refetchMe } = useQuery(["Me"], Me, { enabled: false });
  const { data: cardsData } = useQuery(["CustomerCards", user.accountId], CustomerCards);
  const { data: invoicesData } = useQuery(["CustomerInvoices", user.accountId], CustomerInvoices);
  const { data: workspacesData } = useQuery(["Workspaces"], Workspaces);
  
  // Mutations
  const createUserMutation = useMutation(CreateUser);
  const createTeamMutation = useMutation(CreateTeam);
  const createWorkspaceMutation = useMutation(CreateWorkspace);
  
  const handleMenuClick = (event, type) => {
    setAnchorEl(event.currentTarget);
    setMenuType(type);
  };
  
  const handleMenuClose = () => {
    setAnchorEl(null);
    setMenuType('');
  };
  
  const handleDialogOpen = (type) => {
    setDialogType(type);
    setDialogOpen(true);
    setShowResult(false);
    setResultMessage('');
    handleMenuClose();
  };
  
  const handleDialogClose = () => {
    setDialogOpen(false);
    setDialogType('');
    setSelectedValue('');
    setShowResult(false);
    setResultMessage('');
    setIsLoading(false);
  };
  
  const handleRefreshData = () => {
    refetchMe();
    queryClient.invalidateQueries();
  };
  
  const handleTestConnection = async () => {
    if (!selectedValue) return;
    
    setIsLoading(true);
    try {
      await TestDatabaseConnection(selectedValue);
      setResultMessage('Database connection successful!');
    } catch (error) {
      setResultMessage('Database connection failed: ' + (error.message || 'Unknown error'));
    }
    setIsLoading(false);
    setShowResult(true);
  };
  
  const actionItems = [
    { icon: <PaymentIcon />, text: 'View Payment Methods', action: 'dialog', type: 'payment' },
    { icon: <InvoiceIcon />, text: 'View Payment History', action: 'dialog', type: 'invoices' },
    { icon: <TestIcon />, text: 'Test Database Connection', action: 'dialog', type: 'test' },
    { icon: <RefreshIcon />, text: 'Refresh Account Data', action: 'direct', type: 'refresh' }
  ];
  
  // Add admin-only items
  if (isAdmin) {
    actionItems.splice(3, 0, 
      { icon: <CreateUserIcon />, text: 'Create New User', action: 'menu', type: 'createUser' },
      { icon: <CreateTeamIcon />, text: 'Create New Team', action: 'menu', type: 'createTeam' },
      { icon: <CreateWorkspaceIcon />, text: 'Create New Workspace', action: 'menu', type: 'createWorkspace' }
    );
  }
  
  const handleItemClick = (item, e) => {
    if (item.action === 'direct' && item.type === 'refresh') {
      handleRefreshData();
    } else if (item.action === 'menu') {
      handleMenuClick(e, item.type);
    } else if (item.action === 'dialog') {
      handleDialogOpen(item.type);
    }
  };
  
  const renderDialogContent = () => {
    if (showResult) {
      return (
        <Alert severity={resultMessage.includes('successful') ? 'success' : 'error'}>
          {resultMessage}
        </Alert>
      );
    }
    
    if (isLoading) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <CircularProgress size={24} />
          <Typography>Testing connection...</Typography>
        </div>
      );
    }
    
    switch (dialogType) {
      case 'payment':
        return (
          <div>
            <Typography variant="h6" gutterBottom>Payment Methods</Typography>
            {cardsData?.data?.map((card) => (
              <Typography key={card.id} variant="body2" paragraph>
                {card.brand} **** **** **** {card.last4}
                {card.default_source && ' (Default)'}
              </Typography>
            )) || <Typography>No payment methods found</Typography>}
          </div>
        );
      case 'invoices':
        return (
          <div>
            <Typography variant="h6" gutterBottom>Payment History</Typography>
            {invoicesData?.data?.slice(0, 5).map((invoice) => (
              <Typography key={invoice.id} variant="body2" paragraph>
                ${(invoice.amount_paid / 100).toFixed(2)} - {new Date(invoice.created * 1000).toLocaleDateString()}
              </Typography>
            )) || <Typography>No payment history found</Typography>}
          </div>
        );
      case 'test':
        return (
          <FormControl fullWidth margin="normal">
            <InputLabel>Select Workspace</InputLabel>
            <Select
              value={selectedValue}
              onChange={(e) => setSelectedValue(e.target.value)}
              label="Select Workspace"
            >
              {workspacesData?.data?.map((workspace) => (
                <MenuItem key={workspace.id} value={workspace.id}>
                  {workspace.name}
                </MenuItem>
              )) || []}
            </Select>
          </FormControl>
        );
      default:
        return null;
    }
  };
  
  const getDialogTitle = () => {
    switch (dialogType) {
      case 'payment':
        return 'Payment Methods';
      case 'invoices':
        return 'Payment History';
      case 'test':
        return 'Test Database Connection';
      default:
        return 'Quick Action';
    }
  };
  
  const getDialogActions = () => {
    if (showResult || dialogType === 'payment' || dialogType === 'invoices') {
      return (
        <Button onClick={handleDialogClose}>Close</Button>
      );
    }
    
    if (dialogType === 'test') {
      return (
        <>
          <Button onClick={handleDialogClose}>Cancel</Button>
          <Button 
            onClick={handleTestConnection} 
            variant="contained"
            disabled={!selectedValue || isLoading}
          >
            Test Connection
          </Button>
        </>
      );
    }
    
    return <Button onClick={handleDialogClose}>Close</Button>;
  };
  
  return (
    <Paper 
      variant="outlined"
      sx={{
        borderRadius: borderRadius,
        border: `${border}px solid`,
        borderColor: borderColor
      }}
    >
      <Typography variant="h6" sx={{ p: 2, pb: 1 }}>
        Quick Actions
      </Typography>
      <List dense>
        {actionItems.map((item, index) => (
          <ListItem 
            key={index}
            button
            onClick={(e) => handleItemClick(item, e)}
          >
            <ListItemIcon>
              {item.icon}
            </ListItemIcon>
            <ListItemText primary={item.text} />
          </ListItem>
        ))}
      </List>
      
      {/* Menu for create actions */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        {menuType === 'createUser' && (
          <MenuItem onClick={() => { window.location.href = '/create-user'; handleMenuClose(); }}>
            Open User Form
          </MenuItem>
        )}
        {menuType === 'createTeam' && (
          <MenuItem onClick={() => { window.location.href = '/teams'; handleMenuClose(); }}>
            Open Team Form
          </MenuItem>
        )}
        {menuType === 'createWorkspace' && (
          <MenuItem onClick={() => { window.location.href = '/workspaces/create'; handleMenuClose(); }}>
            Open Workspace Form
          </MenuItem>
        )}
      </Menu>
      
      {/* Dialog for view/test actions */}
      <Dialog open={dialogOpen} onClose={handleDialogClose} maxWidth="sm" fullWidth>
        <DialogTitle>{getDialogTitle()}</DialogTitle>
        <DialogContent>
          {renderDialogContent()}
        </DialogContent>
        <DialogActions>
          {getDialogActions()}
        </DialogActions>
      </Dialog>
    </Paper>
  );
};

export default QuickRightPanel;